package com.bluewap.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.bluewap.api.object.JsonResult;
import com.bluewap.api.object.Transaction;
import com.google.gson.Gson;

public class Util {
	private static URL url;
	private static BufferedReader br = null;
	private static HttpClient httpClient;
	private static PostMethod method;
	private static HttpURLConnection conn;

	public static void printJson(int error, Transaction t, HttpServletResponse resp){
		JsonResult result = new JsonResult();
		result.setError(error);
		if(t != null)
			result.setTransaction(t);
		Gson gson = new Gson();

		try {
			resp.setContentType("application/json");
			PrintWriter out = resp.getWriter();
			out.print(gson.toJson(result));
		} catch (IOException e) {
		}
	}

	public static String buildUrl(String returnUrl, String transId, String token, String msisdn, int result){
		return buildUrl(returnUrl, transId, token, msisdn, "" + result);
	}

	public static String buildUrl(String returnUrl, String transId, String token, String msisdn, String result){
		if(returnUrl.contains("?")) 
			returnUrl = returnUrl +"&";
		else 
			returnUrl = returnUrl +"?";
		returnUrl = returnUrl + "id=" + transId + "&token=" + token + "&result=" + result + "&msisdn=" + msisdn;
		return returnUrl;
	}

	public static boolean isValidUrl(String url){
		if(url.length() > 0 && url.startsWith("http"))
			return true;
		else
			return false;
	}

	public static boolean isValidType(String type){
		try{
			Integer.parseInt(type);
			return true;
		} catch(NumberFormatException e){

		}
		return false;
	}

	public static boolean isValidPrice(String price){
		String[] array = {"0", "500", "1000", "2000", "3000", "4000", "5000", "10000", "15000"};
		return Arrays.asList(array).contains(price);
	}

	public static boolean isValidParam(String param){
		boolean isValid = false;
		if(param!=null && param.length()>0) isValid = true;
		return isValid;
	}
	public static String excuteProcessGET(List<String[]> parameters,
			String getURL) {
		String line;
		BufferedReader rd = null;
		InputStreamReader isr = null;
		StringBuilder result = new StringBuilder();
		StringBuilder urlBuilder = new StringBuilder(getURL);
		try {
			for (int i = 0; i < parameters.size(); i++) {
				try {
					String[] entry = parameters.get(i);
					if (entry[0] != null && entry[1] != null) {
						if (urlBuilder.indexOf("?") == -1) {
							urlBuilder.append("?");
						} else {
							urlBuilder.append("&");
						}

						urlBuilder.append(entry[0]);
						urlBuilder.append("=");
						urlBuilder.append(entry[1]);
					}
				} catch (Exception e) {
				}
			}

			url = new URL(urlBuilder.toString());
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10000);

			isr = new InputStreamReader(conn.getInputStream());
			rd = new BufferedReader(isr);

			while ((line = rd.readLine()) != null) {

				result.append(line);
			}
			rd.close();
		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.disconnect();
					conn = null;
				}

				if (isr != null) {
					isr.close();
					isr = null;
				}

				if (rd != null) {
					rd.close();
					rd = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result.toString();
	}

	public static String excuteProcess(List<String[]> parameters, String postURL) {
		StringBuilder result = null;
		httpClient = new HttpClient();
		method = new PostMethod(postURL);

		for (int i = 0; i < parameters.size(); i++) {
			String[] entry = parameters.get(i);
			if (entry[0] != null && entry[1] != null) {
				method.addParameter(entry[0], entry[1]);
			}
		}

		try {
			int returnCode = httpClient.executeMethod(method);
			if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
				method.getResponseBodyAsString();
			} else {
				result = new StringBuilder();
				br = new BufferedReader(new InputStreamReader(
						method.getResponseBodyAsStream(), "UTF8"));
				String readLine;
				while (((readLine = br.readLine()) != null)) {
					result.append(readLine);
				}
			}

		} catch (Exception e) {
			for (int i = 0; i < parameters.size(); i++) {
				try {
					String[] entry = parameters.get(i);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}

			e.printStackTrace();
		} finally {
			method.releaseConnection();
			httpClient = null;
			if (br != null)
				try {
					br.close();
					br = null;
				} catch (Exception fe) {
				}
		}

		return result.toString();
	}


	public static String post(List<String[]> parameters, String postURL) {
		StringBuffer result = null;
		org.apache.http.client.HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(postURL);
		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		post.setHeader("User-Agent", "Mozilla/5.0");

		for (int i = 0; i < parameters.size(); i++) {
			String[] entry = parameters.get(i);
			urlParameters.add(new BasicNameValuePair(entry[0], entry[1]));
		}
		try {
			post.setEntity(new UrlEncodedFormEntity(urlParameters));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			result = new StringBuffer();
			String line = "";
			while ((line = rd.readLine()) != null) {
				result.append(line);
			}
			// System.out.println(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			client.getConnectionManager().closeExpiredConnections();
		}

		return result.toString();
	}
	public static Map<String, String> getParam (String param){
		Map<String, String> map = new HashMap<String, String>();
		String[] lstparam = param.split("&");
		for(String item:lstparam){
			String key = item.split("=")[0];
			String value = item.split("=")[1];
			map.put(key, value);
		}
		return map;
	}
}
